package com.pj.wisdomlogistics.mvp.model;


import com.google.gson.Gson;
import com.pj.wisdomlogistics.BuildConfig;
import com.pj.wisdomlogistics.entity.HomePageInfo;
import com.pj.wisdomlogistics.entity.response.BaseResponse;
import com.pj.wisdomlogistics.mvp.frame.MvpModel;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.builder.PostFormBuilder;

import java.io.File;
import java.io.IOException;

import okhttp3.Response;
import rx.Observable;
import rx.Subscriber;


public class WisdomLogisticsModel extends MvpModel {
    private static final String POST_URL = BuildConfig.SERVER_HOST + "saveSignPath.do";

    public Observable<BaseResponse<String>> saveSignPath(
            final String userID,
            final File sign
    ) {
        return
                Observable.create(new Observable.OnSubscribe<BaseResponse<String>>() {
                    @Override
                    public void call(Subscriber<? super BaseResponse<String>> subscriber) {
                        PostFormBuilder formBuilder = OkHttpUtils.post().url(POST_URL);
                        formBuilder.addParams("userID", userID);
                        if(sign != null){
                            formBuilder.addFile("sign", sign.getAbsolutePath() , sign);
                        }

                        try {
                            Response response = formBuilder.build().execute();
                            String str = response.body().string();
                            BaseResponse<String> postResponse = new Gson().fromJson(str, BaseResponse.class);
                            subscriber.onNext(postResponse);
                            subscriber.onCompleted();
                        } catch (IOException e) {
                            e.printStackTrace();
                            subscriber.onError(e);
                        }
                    }
                });
    }

    public Observable<BaseResponse<HomePageInfo>> home(String userID){
        return mApiService.home(userID);
    }

}
